package com.qk.management.controller;

import com.qk.common.api.BdMapIpApi;
import com.qk.common.api.BdMapWeatherApi;
import com.qk.common.enums.BizEnum;
import com.qk.common.property.BdMapProperties;
import com.qk.common.util.IPUtils;
import com.qk.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author:gzc
 * @Date: 2025/10/09 14:28
 * @Description:
 */
@RestController
@Slf4j
public class WeatherController {

    @Autowired
    private BdMapIpApi bdMapIpApi;
    @Autowired
    private BdMapWeatherApi bdWeatherApi;
    @Autowired
    private BdMapProperties bdMapProperties;

    @GetMapping("/weather/baidu")
    public Result getWeather(HttpServletRequest  request) throws Exception {
//        String clientIp = "39.171.252.132"; // 示例公网IP
        //开发环境下还无法获取公网IP,要么通过硬编码写死公网IP进行测试,要么进行内网穿透
        //生产环境中若使用代理服务器,还需在代理服务器中配置传递用户真实的公网IP,以便后端接口动态获取公网IP进行解析
        String clientIp = IPUtils.getClientIp(request);
        log.info("客户端IP地址：{}", clientIp);
        Map<String,String> IpParams = new LinkedHashMap<>();
        IpParams.put("ip", clientIp);
        IpParams.put("coor", "bd09ll");
        IpParams.put("ak", bdMapProperties.getAk());
        String addressCode = bdMapIpApi.getIpInfo(bdMapProperties.getIpUrl(), IpParams);
        if (addressCode == null){
            throw new Exception(BizEnum.ADDRESS_CODE_ERROR.getMsg());
        }
        log.info("获取区域编码成功：{}", addressCode);
        Map<String, String> weatherParams = new LinkedHashMap<>();
        weatherParams.put("district_id", addressCode);
        weatherParams.put("data_type", "all");
        weatherParams.put("ak", bdMapProperties.getAk());
        Map<String, Object> weather = bdWeatherApi.getWeather(bdMapProperties.getWeatherUrl(), weatherParams);
        if (weather == null){
            throw new Exception(BizEnum.WEATHER_ERROR.getMsg());
        }
        log.info("获取天气数据成功：{}", weather);
        return Result.success(weather);
    }
}
